<template>
  <div class="login">
    <div ref="vantaRef" style="width: 100%; height: 100vh"></div>
    <div class="my_title">
      <div>Login&Register</div>
      <div class="small_title">一款智能在线个人照片库！</div>
    </div>
    <!-- 登录表单容器 -->
    <div class="login-wrapper">
      <!-- 登录标题 -->
      <h1 class="title">
        <i class="el-icon-house"></i>
        凌烟阁智能照片整理
      </h1>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="登录" name="first">
          <el-form
                  :model="loginForm"
                  status-icon
                  :rules="rules"
                  ref="loginForm"
                  label-width="100px"
                  class="loginForm"
                  hide-required-asterisk
          >
            <el-form-item label="账号" prop="username">
              <el-input
                      size="small"
                      type="text"
                      v-model="loginForm.username"
                      autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input
                      size="small"
                      type="password"
                      v-model="loginForm.password"
                      autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                      type="primary"
                      @click="submitForm('loginForm')"
                      size="small"
              >登录</el-button
              >

              <el-button @click="resetForm('loginForm')" size="small"
              >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="注册" name="second">

          <el-form
                  :model="signForm"
                  status-icon
                  :rules="rules"
                  ref="signForm"
                  label-width="100px"
                  class="loginForm"
                  hide-required-asterisk
          >
            <el-form-item label="账号" prop="username">
              <el-input
                      size="small"
                      type="text"
                      v-model="signForm.username"
                      autocomplete="off"
              ></el-input>
            </el-form-item>

            <el-form-item label="密码" prop="password">
              <el-input
                      size="small"
                      type="password"
                      v-model="signForm.password"
                      autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                      type="primary"
                      @click="SignUpForm('signForm')"
                      size="small"
              >注册</el-button
              >

              <el-button @click="resetForm('signForm')" size="small"
              >重置</el-button
              >
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <router-view />
  </div>
</template>

<script>
    import * as THREE from "three";
    import BIRDS from "vanta/src/vanta.birds";

    export default {
        data() {
            // 包含特殊字符的函数
            const checkSpecificKey = (str) => {
                var specialKey =
                    "[`~!#$^&*()=|{}':;',\\[\\].<>/?~！#￥……&*（）——|{}【】‘；：”“'。，、？]‘'";
                for (var i = 0; i < str.length; i++) {
                    if (specialKey.indexOf(str.substr(i, 1)) != -1) {
                        return false;
                    }
                }
                return true;
            };
            //验证账号函数
            const username = (rule, value, callback) => {
                if (!checkSpecificKey(value)) {
                    callback(new Error("用户名不能包含特殊字符"));
                }
                callback();
            };
            //验证密码函数
            const pass = (rule, value, callback) => {
                if (value === "") {
                    callback(new Error("请输入密码"));
                } else if (!checkSpecificKey(value)) {
                    callback(new Error("密码不能包含特殊字符"));
                } else {
                    callback();
                }
                /*       else {
                    if (this.loginForm.checkPass !== "") {
                      this.$refs.loginForm.validateField("checkPass");
                    }
                    callback();
                  } */
            };
            //确认密码验证函数
            /*     const checkPwd = (rule, value, callback) => {
                if (value === "") {
                  callback(new Error("请再次输入密码"));
                } else if (value !== this.loginForm.password) {
                  callback(new Error("两次输入密码不一致!"));
                } else {
                  callback();
                }
              }; */
            return {
                activeName: "first",
                signForm:{
                    username: "",
                    password: "",
                },

                loginForm: {
                    username: "",
                    password: "",
                    /*         checkPass: "" */
                },
                rules: {
                    username: [
                        { validator: username, trigger: "blur" },
                        { required: true, message: "请输入账号", trigger: "blur" },
                        { min: 3, max: 6, message: "账号长度在 3 - 6 位", trigger: "blur" },
                    ],
                    password: [
                        { required: true, validator: pass, trigger: "blur" },
                        { min: 3, max: 6, message: "密码长度在 3 - 6 位", trigger: "blur" },
                    ],
                    /*  checkPass: [{ required: true, validator: checkPwd, trigger: "blur" }] */
                },
            };
        },

        mounted() {
            this.vantaEffect = BIRDS({
                el: this.$refs.vantaRef,
                THREE: THREE,
            });
        },
        beforeDestroy() {
            if (this.vantaEffect) {
                this.vantaEffect.destroy();
            }
        },
        methods: {
            handleClick(tab, event) {
                console.log(tab, event);
            },
            //登录验证
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //收集账号密码
                        /*           let params = {
                            username: this.loginForm.username,
                            password: this.loginForm.password
                          }; */
                        //使用axios发送数据
                        this.$axios
                            .post("/user/login", {
                                username: this.loginForm.username,
                                password: this.loginForm.password
                            })
                            .then((response) => {
                                console.log(response);
                                //接收数据
                                /*  let { error_code, reason, token, username } = response.data; */
                                if (response.data.code === 0) {
                                    // 把token存在浏览器的本地存储中
                                    // window.sessionStorage.setItem("token", response.token);
                                    // console.log(response.token);
                                    // 把username存在浏览器的本地存储中
                                    window.sessionStorage.setItem(
                                        "username",
                                        this.loginForm.username
                                    );
                                    //将ID存入浏览器本地储存中
                                    window.sessionStorage.setItem("uId", response.data.uId);
                                    window.sessionStorage.setItem("isLogin",true);
                                    // yes.valueOf()
                                    this.$message({
                                        //弹出成功提示
                                        showClose: true,
                                        type: "success",
                                        message: "登录成功",
                                    });
                                    // 跳转到后端主页
                                    this.$router.push("/index");
                                }
                                else {
                                    this.$message.error("登录失败!");
                                }
                                // else if (response.code === 203) {
                                //   this.$message.error("账号或密码错误");
                                // } else if (response.code === 204) {
                                //   this.$message.warning("用户已登录过");
                                // } else {
                                //   //弹出失败提示
                                // this.$message.error("失败");
                                // }
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    } else {
                        this.$message.error("登录失败!");
                        return false;
                    }
                });
            },
            SignUpForm(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        //收集账号密码
                        /*           let params = {
                            username: this.loginForm.username,
                            password: this.loginForm.password
                          }; */
                        //使用axios发送数据
                        this.$axios
                            .post("/user/register", {
                                username: this.signForm.username,
                                password: this.signForm.password
                            })
                            .then((response) => {
                                //接收数据
                                /*  let { error_code, reason, token, username } = response.data; */
                                if (response.data.code === 0) {
                                    // 把token存在浏览器的本地存储中
                                    // window.sessionStorage.setItem("token", response.token);
                                    // console.log(response.token);
                                    // 把username存在浏览器的本地存储中
                                    // window.sessionStorage.setItem(
                                    //     "username",
                                    //     this.signForm.username
                                    // );
                                    //将ID存入浏览器本地储存中
                                    // console.log("成功",response)
                                    // window.sessionStorage.setItem("uId", response.data.uId);
                                    // yes.valueOf()
                                    this.$message({
                                        //弹出成功提示
                                        showClose: true,
                                        type: "success",
                                        message: "注册成功",
                                    });
                                    // 跳转到后端主页
                                    // this.$router.push("/personal");
                                }
                                else {
                                    this.$message.error("注册失败!");
                                }
                                // else if (response.code === 203) {
                                //   this.$message.error("账号或密码错误");
                                // } else if (response.code === 204) {
                                //   this.$message.warning("用户已登录过");
                                // } else {
                                //   //弹出失败提示
                                // this.$message.error("失败");
                                // }
                            })
                            .catch((err) => {
                                console.log(err);
                            });
                    } else {
                        this.$message.error("注册失败!");
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
        },
    };
</script>

<style lang="less">
  .login {
    height: 100%;
    .login-wrapper {
      width: 300px;
      height: 250px;
      border-radius: 10px;
      background-color: rgba(251, 250, 250, 0);
      color: #ffffff94;
      // 垂直水平居中
      position: fixed;
      top: 10%;
      right: 0;
      bottom: 0;
      left: 40%;
      margin: auto;
      padding: 20px 20px 16px;
      .title {
        margin: 0 0 20px;
        font-size: 25px;
        height: 30px;
        line-height: 50px;
      }
      .el-form {
        .el-form-item {
          .el-form-item__label {
            color: #ffffff;
          }
        }
      }
    }
  }
  .my_title {
    z-index: 999;
    position: fixed;
    top: 30%;
    left: 5%;
    color: rgb(237, 245, 243);
    font-size: 60px;
    font-weight: bolder;
    .small_title {
      z-index: 999;
      position: fixed;
      top: 45%;
      left: 5%;
      color: rgb(237, 245, 243);
      font-size: 20px;
      font-weight: bolder;
    }
  }
</style>
